package com.screx.mcloud.lib.view.web

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.text.TextUtils
import com.tencent.smtt.export.external.interfaces.WebResourceError
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.export.external.interfaces.WebResourceResponse
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import qsos.lib.base.callback.OnTListener
import qsos.lib.base.utils.ToastUtils
import timber.log.Timber


/**
 * 监听网页链接:
 * - 根据标识:打电话、发短信、发邮件
 * - 进度条的显示
 * - 添加javascript监听
 * - 唤起京东，支付宝，微信原生App
 */
class WebViewClient(
    private val mActivity: Activity,
    private val mStatusListener: OnTListener<Int>? = null
) : WebViewClient() {

    private var mWebView: WebView? = null

    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
        if (TextUtils.isEmpty(url)) {
            return false
        }
        if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("ftp")) {
            return false
        }
        handleOtherwise(mActivity, url)
        return true
    }

    override fun onPageFinished(view: WebView, url: String) {
        super.onPageFinished(view, url)
        mStatusListener?.back(1)
    }

    override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
        super.onPageStarted(view, url, favicon)
        this.mWebView = view
        mStatusListener?.back(0)
    }

    override fun onReceivedError(
        view: WebView?,
        request: WebResourceRequest?,
        error: WebResourceError?
    ) {
        super.onReceivedError(view, request, error)
        Timber.tag("网页加载日志")
            .w("CODE=onReceivedError 网页错误URL=${request?.url} 错误信息=${error?.toString()}")
    }

    override fun onReceivedHttpError(
        view: WebView?,
        request: WebResourceRequest?,
        errorResponse: WebResourceResponse?
    ) {
        super.onReceivedHttpError(view, request, errorResponse)
        Timber.tag("网页加载日志")
            .w("CODE=onReceivedHttpError 网页错误URL=${request?.url} 错误信息=${errorResponse?.toString()}")
    }

    override fun onReceivedError(
        view: WebView,
        errorCode: Int,
        description: String,
        failingUrl: String
    ) {
        super.onReceivedError(view, errorCode, description, failingUrl)
        Timber.tag("网页加载日志")
            .w("CODE=$errorCode 网页错误URL=$failingUrl 错误信息=$description")
        when (errorCode) {
            401 -> {
                ToastUtils.showToast(view.context, "网页部分信息需登录")
            }
            else -> {
                view.loadUrl("about:blank")
            }
        }
        mStatusListener?.back(-1)
    }

    // 返回页面被放大的问题
    override fun onScaleChanged(view: WebView, oldScale: Float, newScale: Float) {
        super.onScaleChanged(view, oldScale, newScale)
        if (newScale - oldScale > 7) {
            // 异常放大，缩回去。
            view.setInitialScale((oldScale / newScale * 100).toInt())
        }
    }

    /**网页里可能唤起其他的app*/
    private fun handleOtherwise(activity: Activity, url: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addCategory(Intent.CATEGORY_BROWSABLE)
        intent.data = Uri.parse(url)
        activity.startActivity(intent)
    }

}
